package logic

import (
	"context"
	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"grpc-common/market/types/market"
	"market/internal/domain"
	"market/internal/svc"
	"time"
)

type MarketLogic struct {
	ctx                context.Context
	svcCtx             *svc.ServiceContext
	exchangeCoinDomain *domain.ExchangeCoinDomain
	marketDomain       *domain.MarketDomain
	coinDomain         *domain.CoinDomain
	logx.Logger
}

func NewMarketLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MarketLogic {
	return &MarketLogic{
		ctx:                ctx,
		svcCtx:             svcCtx,
		Logger:             logx.WithContext(ctx),
		exchangeCoinDomain: domain.NewExchangeCoinDomain(svcCtx.Db),
		marketDomain:       domain.NewMarketDomain(svcCtx.MongoClient),
		coinDomain:         domain.NewCoinDomain(svcCtx.Db),
	}
}

/*
*
查找货币信息
*/
func (l *MarketLogic) FindCoinInfo(in *market.MarketReq) (*market.Coin, error) {
	coin := l.coinDomain.FindByUnit(l.ctx, in.Unit)
	_coin := &market.Coin{}
	err := copier.Copy(_coin, coin)
	if err != nil {
		return &market.Coin{}, err
	}
	return _coin, nil
}
func (l *MarketLogic) FindSymbolInfo(in *market.MarketReq) (*market.ExchangeCoin, error) {
	exchangeCoin := l.exchangeCoinDomain.FindBySymbol(l.ctx, in.Symbol)
	_exchangeCoin := &market.ExchangeCoin{}
	err := copier.Copy(_exchangeCoin, exchangeCoin)
	if err != nil {
		return &market.ExchangeCoin{}, err
	}
	return _exchangeCoin, nil
}

/*
*
获取币种行情
*/
func (l *MarketLogic) FindSymbolThumbTrend(in *market.MarketReq) (*market.SymbolThumbRes, error) {
	//先造一个假的数据
	coins := l.exchangeCoinDomain.FindVisible(context.Background())
	coinThumbs := make([]*market.CoinThumb, len(coins))
	//读取mongodb的数据
	coinThumbs = l.marketDomain.SymbolThumbTrend(coins)
	//测试数据
	/*for i, v := range coins {
		ct := &market.CoinThumb{}
		ct.Symbol = v.Symbol
		trend := make([]float64, 0)
		for p := 0; p < 24; p++ {
			trend = append(trend, rand.Float64())
		}
		ct.Trend = trend
		coinThumbs[i] = ct
	}*/
	return &market.SymbolThumbRes{List: coinThumbs}, nil
}

func (l *MarketLogic) HistoryKline(req *market.MarketReq) (*market.HistoryRes, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	period := "1H"
	if req.Resolution == "60" {
		period = "1H"
	} else if req.Resolution == "30" {
		period = "30m"
	} else if req.Resolution == "15" {
		period = "15m"
	} else if req.Resolution == "5" {
		period = "5m"
	} else if req.Resolution == "1" {
		period = "1m"
	} else if req.Resolution == "1D" {
		period = "1D"
	} else if req.Resolution == "1W" {
		period = "1W"
	} else if req.Resolution == "1M" {
		period = "1M"
	}
	histories, err := l.marketDomain.HistoryKline(ctx, req.Symbol, req.From, req.To, period)
	if err != nil {
		return nil, err
	}
	return &market.HistoryRes{
		List: histories,
	}, nil
}
